/*
 * @Author: caiyongqiang
 * @Date: 2022-10-18 16:46:07
 * @LastEditTime: 2022-10-27 10:02:33
 * @LastEditors: caiyongqiang
 * @Description: 二次封装组件WeCropper,更高级用法可自行引入文件编辑
 *
 * 使用方法：
 *
 * wxml:
 * <ImgCropper id="imgCorpprt"  use2d
 *   cutWidth="{{300}}"  cutHeight="{{300}}"
 *   bind:onCorpperOk="onCorpperOk">
 * </ImgCropper>
 *
 * ts：
 * // 把图片设置渲染，调用方法：
 * that.selectComponent('#imgCorpprt').initOpenCropper(src)
 *
 * // 裁剪图片输出，方法：
 * onCorpperOk(e: any) {
 *   console.log(e.detail.path, 'path')
 * }
 */

import WeCropper from '../we-cropper/we-cropper.js'
import { compareVersion } from '../../utils/util'

const systemInfo = wx.getSystemInfoSync()
const width = systemInfo.windowWidth
const height = systemInfo.windowHeight - 50

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    /** 是否强制使用2d渲染 */
    use2d: {
      type: Boolean,
      value: false
    },
    /** 复杂参数配置信息 */
    cropperOpt: {
      type: Object,
      value: <CropperOpt>{}
    },
    /** 基础配置-裁剪框的大小,单位:px */
    cutWidth: {
      type: Number,
      value: 0
    },
    cutHeight: {
      type: Number,
      value: 0
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    /**默认配置信息*/
    defCropperOpt: {
      id: 'cropper',
      targetId: 'targetCropper',
      pixelRatio: systemInfo.pixelRatio,
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 300) / 2,
        y: (height - 300) / 2,
        width: 300,
        height: 300
      },
      boundStyle: {
        color: '#04b00f',
        mask: 'rgba(0,0,0,0.3)',
        lineWidth: 1
      }
    } as CropperOpt,
    isShowCanvas: false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /** 初始化组件及判断使用canvas */
    initOpenCropper(this: any, src: string) {
      // 显示渲染canvas
      this.setData({ isShowCanvas: true })

      /** 如果已经渲染过，无需重新获取canvas节点*/
      if (this.cropper?.pushOrign) {
        this.cropper.pushOrign(src)
        return
      }

      let { cropperOpt, defCropperOpt } = this.data
      /** 合并默认配置信息 */
      defCropperOpt = Object.assign(defCropperOpt, cropperOpt)
      defCropperOpt.component_this = this

      /** 判断是否传入裁剪框大小 */
      if (this.data.cutWidth) {
        const cutWidth = this.data.cutWidth
        const cutHeight = this.data.cutHeight
        defCropperOpt.cut.x = (width - cutWidth) / 2
        defCropperOpt.cut.y = (height - cutHeight) / 2
        defCropperOpt.cut.width = cutWidth
        defCropperOpt.cut.height = cutHeight
      }

      /** 判断2d渲染模式
       * 2d渲染最低要求：
       * 1、PC端还不支持2d渲染
       * 2、基础库不能低于2.9.0
      */
      const isMiniRequire = compareVersion(systemInfo.SDKVersion, '2.10.5') && !/windows|mac/.test(systemInfo.platform)
      if (this.data.use2d && isMiniRequire) {

        this.createSelectorQuery().select(`#${defCropperOpt.id}`).fields({ node: true, size: true }).exec((res: any) => {

          if (!res || !res[0]) {
            return wx.showToast({ title: '页面初始化失败，请销后重试', icon: 'none' })
          }

          const canvas = res[0].node
          const ctx = canvas.getContext('2d')
          const dpr = systemInfo.pixelRatio

          canvas.width = res[0].width * dpr
          canvas.height = res[0].height * dpr
          ctx.scale(dpr, dpr)
          defCropperOpt.canvas = canvas
          defCropperOpt.ctx = ctx

          this.setData({ defCropperOpt })
          this.initCropper(src)
        })

      } else {

        this.initCropper(src)

      }
    },
    /** 初始化cropper方法 */
    initCropper(this, src: string) {
      const { defCropperOpt } = this.data
      this.cropper = new (WeCropper as any)(defCropperOpt)
        .on('ready', (ctx: any) => {
          console.log(`wecropper is ready for work!`, ctx)
          ctx.pushOrign(src)
        })
        .on('beforeImageLoad', (ctx: any) => {
          wx.showToast({
            title: '上传中',
            icon: 'loading',
            duration: 20000
          })
        })
        .on('imageLoad', (ctx: any) => {
          wx.hideToast()
        })
    },
    /** 手势滑动开始 */
    touchStart(this: { cropper: Cropper }, e: WechatMiniprogram.TouchEvent) {
      this.cropper.touchStart(e)
    },
    /** 手势移动 */
    touchMove(this: { cropper: Cropper }, e: WechatMiniprogram.TouchEvent) {
      this.cropper.touchMove(e)
    },
    /** 手势滑动结束 */
    touchEnd(this: { cropper: Cropper }, e: WechatMiniprogram.TouchEvent) {
      this.cropper.touchEnd(e)
    },
    /** 裁剪图片输出方法 */
    getCropperImage(this: { cropper: Cropper, triggerEvent: any, setData: any }) {
      this.cropper.getCropperImage({})
        .then((path: string) => {
          /** 生成海报输出到父组件 */
          this.triggerEvent('onCorpperOk', { path })
          /** 图片生成隐藏canvas */
          this.cropper.removeImage()
          this.setData({ isShowCanvas: false })
        })
        .catch((err: any) => {
          wx.showModal({
            title: '温馨提示',
            content: err && err.message || '图片裁剪失败！'
          })
        })
    },
    /** 重新上传裁剪图片 */
    uploadTap(this: { cropper: Cropper }) {
      const self = this
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success(res) {
          const src = res.tempFilePaths[0]
          /** 获取裁剪图片资源后，给cropper添加src属性及其值 */
          self.cropper.removeImage()
          self.cropper.pushOrign(src)
        }
      })
    }
  }
})